using MongoDB.Driver.Linq;
using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Util;


namespace Geekeradmin.ExtendsService
{
    /// <summary>
    /// 
    /// </summary>
    public class DowntaskService : BackgroundService
    {
        private readonly IMySqlSugarService mySqlSugar;
        private readonly IWebHostEnvironment env;

        /// <summary>
        /// 初始化依赖注入
        /// </summary>
        /// <param name="mySqlSugar"></param>
        public DowntaskService(IMySqlSugarService mySqlSugar, IWebHostEnvironment env)
        {
            this.mySqlSugar = mySqlSugar;
            this.env = env;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await base.StartAsync(cancellationToken);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await base.StopAsync(cancellationToken);
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await Task.Delay(60000, stoppingToken); //启动后三分钟执行一次
                InitTask();
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(180000, stoppingToken); //启动后三分钟执行一次
                    if (DateTime.Now.Day==1 && DateTime.Now.Hour == 0 && DateTime.Now.Minute <= 5)
                    {
                        InitTask();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void InitTask()
        {
            Task.Factory.StartNew(() =>
            {
                var table = TableAtributeUtil.GetTable<Downtask>();
                var lastmonth=DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
                var sql = $"select Id,furl from {table} where left(ctime,7) ='{lastmonth}';";
                var list = mySqlSugar.Query<Downtask>(sql,null,out var msg);
                if(string.IsNullOrEmpty(msg) && list!=null && list.Count > 0)
                {
                    var Idlist = list.Select(o => o.Id);
                    var filelist = list.Select(o => o.furl);
                    sql = $"delete from {table} where Id in({String.Join(",",Idlist)});";
                    mySqlSugar.ExecuteSql(sql, null, out msg);
                    if (string.IsNullOrEmpty(msg))
                    {
                        foreach (var item in filelist)
                        {
                            var path = EnDecryptionUtil.DESDecryptbyqd(item);
                            var filepath = this.env.WebRootPath + path;
                            if (FileUtil.Exists(filepath))
                            {
                                FileUtil.DelFile(filepath);
                            }
                        }
                    }
                }
            });
        }
    }
}
